'use strict';

const BaseModel = require('./BaseModel');

class AdminUsersModel extends BaseModel {

  constructor() {
    super('admin_users', 'id');
    this.entity = class entity {
      constructor() {
        this.id = null;
        this.loginName = null;
        this.loginPwd = null;
        this.state = null;
        this.realName = null;
        this.gender = null;
        this.branchCode = null;
        this.remarks = null;
        this.creator = null;
        this.createTime = null;
        this.updateTime = null;
        // 增加字段
        this.branchName = null;
      }
    };
  }

  // 根据用户名查询用户信息
  async findOneByName(app, uname) {
    let userinfo = new this.entity();
    const dbentity = await app.mysql.get(this.tableName, { login_name: uname });
    if (dbentity) {
      userinfo = this.transformation_Entity(dbentity);
      return userinfo;
    }
    return null;
  }

  async selectAdminUsersList(app, wheres) {
    const sqls = [];
    sqls.push(
      `SELECT
          u.id,
          u.login_name,
          u.state,
          u.real_name,
          u.gender,
          u.branch_code,
          u.remarks,
          u.create_time,
          u.update_time,
          aurr.role_id,
          r.role_name
        FROM
          admin_users u
          INNER JOIN admin_user_role_rel aurr ON u.id = aurr.admin_user_id
          INNER JOIN admin_roles r on r.id = aurr.role_id where 1=1`
    );
    // 登录名模糊查询
    if (wheres.loginName) sqls.push(` and u.login_name like \'%${wheres.loginName}%\' `);
    // 状态
    if (typeof wheres.state === 'number') sqls.push(` and u.state = ${wheres.state} `);
    // 角色ID
    if (wheres.roleId) sqls.push(` and aurr.role_id = ${wheres.roleId} `);
    // 单位
    if (wheres.branchCode) sqls.push(` and u.branch_code like '%${wheres.branchCode}%' `);
    // 开始时间
    if (wheres.startDate) sqls.push(` and u.create_time >= '${wheres.startDate}'`);
    // 结束时间
    if (wheres.endDate) sqls.push(` and u.create_time <= '${wheres.endDate}'`);
    // orders
    // if (orders && orders.length > 0) sqls.push(' order by create_time desc ');
    sqls.push(' order by u.create_time desc ');
    // 分页
    sqls.push(` limit ${(wheres.pageIndex - 1) * wheres.pageSize},${wheres.pageSize} `);
    const sql = sqls.join('');
    app.logger.debug('SQL:', sql);
    
    const results = await app.mysql.query(sql);
    
    if (results) {
      const adminUsersList = [];
      for (const dbentity of results) {
        let adminUsers = new this.entity();
        adminUsers = this.transformation_Entity(dbentity);
        adminUsersList.push(adminUsers);
      }
      return adminUsersList;
    }
    return null;
  }

  async selectAdminUsersListCount(app, wheres) {
    const sqls = [];
    sqls.push(
      `SELECT
          count(1) as dataCount
        FROM
          admin_users u
          INNER JOIN admin_user_role_rel aurr ON u.id = aurr.admin_user_id
          INNER JOIN admin_roles r on r.id = aurr.role_id where 1=1 `
    );
    // 登录名模糊查询
    if (wheres.loginName) sqls.push(` and u.login_name like \'%${wheres.loginName}%\' `);
    // 状态
    if (typeof wheres.state === 'number') sqls.push(` and u.state = ${wheres.state} `);
    // 角色ID
    if (wheres.roleId) sqls.push(` and aurr.role_id = ${wheres.roleId} `);
    // 单位
    if (wheres.branchCode) sqls.push(` and u.branch_code like '%${wheres.branchCode}%' `);
    // 开始时间
    if (wheres.startDate) sqls.push(` and u.create_time >= '${wheres.startDate}'`);
    // 结束时间
    if (wheres.endDate) sqls.push(` and u.create_time <= '${wheres.endDate}'`);
    
    const sql = sqls.join('');
    app.logger.debug('SQL:', sql);
    
    const results = await app.mysql.query(sql);
    if (results && results.length > 0) {
      return results[0].dataCount;
    }
    return 0;
  }
  
  async findByIdAdminUserInfo(app, id) {
    const sql = `select 
                  u.id,
                  u.login_name,
                  u.state,
                  u.real_name,
                  u.gender,
                  u.branch_code,
                  u.remarks,
                  u.creator,
                  u.create_time,
                  u.update_time,
                  arr.role_id 
                from admin_users u 
                INNER JOIN admin_user_role_rel arr on u.id = arr.admin_user_id 
                where u.id = '${id}'`;
    app.logger.debug('SQL:', sql);
    const results = await app.mysql.query(sql);
    app.logger.debug('返回的数据：', results);
    if (results && results.length > 0) {
      return this.transformation_Entity(results[0] || '');
    }
    return null;
  }
  
  async updatePwd(app, id, models) {
    return app.mysql.update(this.tableName, models, {
      where: {
        id,
      },
    });
  }
}

module.exports = AdminUsersModel;

